/*
 * $Id$
 */
package py.windmill.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import py.windmill.action.HttpRequest;
import py.windmill.action.HttpResponse;
import py.windmill.action.Request;
import py.windmill.action.RequestMapper;
import py.windmill.action.Route;
import py.windmill.resolution.Tiles;

/**
 *
 * @author myang
 */
public class WindmillFilter implements Filter {

    private RequestMapper _mapper;

    @Override
    public void doFilter(final ServletRequest request,
      final ServletResponse response,
      final FilterChain chain)
      throws IOException, ServletException {
        final Request req = new HttpRequest((HttpServletRequest)request, 
                                            (HttpServletResponse)response);
        final Route rt = _mapper.map(req);
        if (null == rt) {
            chain.doFilter(request, response);
        } else {
            final Execution exec = new Execution();
            exec.execute(rt, req);
        }
    }

    /**
     * Destroy method for this filter
     */
    public void destroy() {
    }

    /**
     */
    public void init(final FilterConfig fc) {
        Application app = app();
        if (null == app) {
            final String s = fc.getInitParameter("Application.class");
            if (null == s) {
            }
            try {
                final Class clz = Class.forName(s);
                app = (Application) clz.newInstance();
            } 
            catch (final Exception ex) {
            }
        }
        _mapper = app.requestMapper();
        final String template = app.jspTemplate();
        if (null != template) {
            fc.getServletContext().setAttribute(Tiles.TILES_TEMPLATE, template);
        }
    }

    public Application app() {
        return null;
    }

}
